using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.customers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.customers
{
    /// <summary>
    /// 添加客户命令处理器
    /// </summary>
    public class AddCustomerCommandHandler : IRequestHandler<AddCustomerCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddCustomerCommandHandler> _logger;

        public AddCustomerCommandHandler(
            IBaseRepository<Customer> customerRepository,
            IMapper mapper,
            ILogger<AddCustomerCommandHandler> logger)
        {
            _customerRepository = customerRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理添加客户命令
        /// </summary>
        /// <param name="request">添加客户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(AddCustomerCommand request, CancellationToken cancellationToken)
        {
            try
            {


                // 验证客户名称是否已存在
                var existingCustomerByName = await _customerRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Name == request.Name && !c.IsDeleted, cancellationToken);

                if (existingCustomerByName != null)
                {
                    return ApiResult<int>.Error("客户名称已存在，请使用其他名称");
                }

                // 如果提供了身份证号，验证身份证号是否已存在（个人客户）
                if (!string.IsNullOrEmpty(request.IdCard))
                {
                    var existingCustomerByIdCard = await _customerRepository.GetAll()
                        .FirstOrDefaultAsync(c => c.IdCard == request.IdCard && !c.IsDeleted, cancellationToken);

                    if (existingCustomerByIdCard != null)
                    {
                        return ApiResult<int>.Error("身份证号已存在，请检查输入");
                    }
                }

                // 如果提供了统一社会信用代码，验证是否已存在（企业客户）
                if (!string.IsNullOrEmpty(request.UnifiedSocialCreditCode))
                {
                    var existingCustomerByCreditCode = await _customerRepository.GetAll()
                        .FirstOrDefaultAsync(c => c.UnifiedSocialCreditCode == request.UnifiedSocialCreditCode && !c.IsDeleted, cancellationToken);

                    if (existingCustomerByCreditCode != null)
                    {
                        return ApiResult<int>.Error("统一社会信用代码已存在，请检查输入");
                    }
                }

                // 验证上级客户ID是否存在（如果提供了的话）
                if (request.SuperiorCustomerId.HasValue && request.SuperiorCustomerId.Value > 0)
                {
                    var superiorCustomer = await _customerRepository.GetAll()
                        .FirstOrDefaultAsync(c => c.Id == request.SuperiorCustomerId.Value && !c.IsDeleted, cancellationToken);

                    if (superiorCustomer == null)
                    {
                        return ApiResult<int>.Error("指定的上级客户不存在或已被删除");
                    }
                }

                // 使用AutoMapper将Command映射为实体
                var customer = _mapper.Map<Customer>(request);

                // 处理上级客户ID：如果为0或未提供，设置为null
                if (!request.SuperiorCustomerId.HasValue || request.SuperiorCustomerId.Value <= 0)
                {
                    customer.SuperiorCustomerId = null;
                }

                // 设置创建时间和创建人
                // 客户编号自动生成：KF+当前时间（精确到秒）
                customer.CustomerCode = "KF" + DateTime.Now.ToString("yyyyMMddHHmmss");
                customer.CreatedTime = DateTime.Now;
                customer.CreatedBy = request.CreatedBy;

                // 添加客户
                var result = await _customerRepository.AddAsync(customer);

                if (result > 0)
                {
                    _logger.LogInformation("成功添加客户，ID: {CustomerId}, 编号: {CustomerCode}, 名称: {CustomerName}", 
                        customer.Id, customer.CustomerCode, customer.Name);
                    
                    return ApiResult<int>.Success(customer.Id, "客户添加成功");
                }
                else
                {
                    _logger.LogError("添加客户失败，编号: {CustomerCode}, 名称: {CustomerName}", 
                        customer.CustomerCode, request.Name);
                    
                    return ApiResult<int>.Error("客户添加失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加客户时发生异常，名称: {CustomerName}", 
                    request.Name);
                
                return ApiResult<int>.Error($"添加客户时发生异常: {ex.Message}");
            }
        }
    }
}
